package com.he.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.he.baseservice.exceptionhandler.EduException;
import com.he.eduservice.entity.EduSubject;
import com.he.eduservice.entity.excel.SubjectData;
import com.he.eduservice.service.EduSubjectService;

public class SubjectExeclListener extends AnalysisEventListener<SubjectData> {


    //因为SubjectExeclListener 不能提交给spring进行管理，需要自己手动new，不能注册其他的对象
//    不能实现数据库操作
    public EduSubjectService subjectService;

    public SubjectExeclListener() {
    }

    public SubjectExeclListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }


    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new EduException(2001, "文件数据为空");
        }
        //一行一行的读取，每次读取的有两个值，第一个是一级分类，第二个是二级分类
        EduSubject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if (existOneSubject == null) {//没有一级分类，进行添加
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(existOneSubject);
        }
        String pid = existOneSubject.getId();
        //判断二级分类
        EduSubject existTwoSubject = this.existTwoSubject(subjectService, subjectData.getOneSubjectName(), pid);
        if (existTwoSubject == null) {//没有一级分类，进行添加
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(existTwoSubject);
        }
    }

    private EduSubject existOneSubject(EduSubjectService subjectService, String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }

    private EduSubject existTwoSubject(EduSubjectService subjectService, String name, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
